<?php
namespace App\Api\V1\Controllers;


use App\Models\HxUsers;
use App\Models\JpushMobile;
use App\Services\Log;
use App\Services\Pusher;
use App\Services\UserService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Usertags;
use App\Models\Tagsname;
use  App\Models\Shareholder;
use App\Models\MemberShip;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{
    /**
     * @return array
     * 注册
     */
    public function register()
    {
        $Userinfo = new User();
        $mobile = IT('mobile',true,'请输入手机号', 10070);  //注册手机号
        $smscode = IT('smscode',true,'请输入短信验证码',10071);  //短信验证码
        $password = IT('password',true,'请输入登录密码',10072);//登录密码
        $openid = IT('openid'); //微信openid
        $unionid =IT('unionid'); //微信unionid
        $Invitation_code =IT('Invitation_code');//邀请码
        $ClientSource = IT('ClientSource',true);
        $registration_id = IT('registration_id');
        $mobile_unique_code = IT('mobile_unique_code',true,'移动设备唯一标识必填',10073);

        if(!preg_match("/^\\d{11}$/",$mobile)){
            EE('手机号必须为11位数字', 0, 10074);
        }
        if(!check_password_format($password)){
            EE('密码必须是6-16位字母数字下划线组合',0, 10075);
        }
        $userInfo = DB::table('users')->where('mobile', $mobile)->first();//注册人信息

        if($userInfo){
            if(!empty($userInfo->password)) {
                EE('该帐号['.$mobile.']已经被注册了',0, 10076);
            }

            if(check_smscode($mobile,$smscode) === false){
                EE('短信验证码不正确',0,10077);
            }
            // 微信、短信登录的账号首次使用密码登录
            $update_rs = User::where('mobile', $mobile)->update(['password' => md5($password)]);
            if($update_rs === false) {
                EE('登录失败！',0, 10083);
            }
            // 校验是否需要发送下线通知
            $ticket = UserService::login_send_jpush($userInfo, ['mobile_unique_code'=>$mobile_unique_code, 'registration_id'=>$registration_id, 'ClientSource'=>$ClientSource]);
            if(empty($ticket)){
                EE('登陆失败！',0, 10083);
            }
            $tags = Usertags::where('uid','=',$userInfo->id)->where('status','=',1)->value('tags');
            return json_success('登录成功',['ticket' => $ticket, 'uid' => $userInfo->id, 'tags' => $tags], 10084);

        }

        if(check_smscode($mobile,$smscode) === false){
            EE('短信验证码不正确',0,10077);
        }
        $data = $Userinfo->register($mobile,$unionid,$openid,$password,$Invitation_code,$registration_id);

        if($data === false){
            EE('注册失败！',0, 10078);
        }else{
            // 保存设备标识
            JpushMobile::saveJpush(['registration_id'=>$registration_id, 'mobile_unique_code'=>$mobile_unique_code]);
        }
        return json_success('注册成功',$data, 10079);
    }
    public function addFriend($introducer, $uid)
    {
        $where_friend = array(
            ['uid', '=', $introducer],
            ['friend_id', '=', $uid],
            ['type', '=', 1]
        );
        $friendInfo = DB::table('friend_user')
            ->where($where_friend)
            ->first();
        if(empty($friendInfo)){
            $insert_friend = [
                'uid' => $introducer,
                'friend_id' => $uid,
                'type' => 1,
                'status' => 1,
                'created_at'    => time2date(),
                'updated_at'    => time2date()
            ];
            $res_friend = D('friend_user')->insert($insert_friend);
        }
    }

    /**
     * @return array
     * 前端登录
     */
    public function login(){

        $MobileNo = IT('mobile',true,'请输入手机号',10070);
        $LoginPwd = IT('password',true,'请输入登录密码',10072);
        $ClientSource = IT('ClientSource',true);
        $registration_id = IT('registration_id');
        $mobile_unique_code = IT('mobile_unique_code',true,'移动设备唯一标识必填',10073);

        $where = array(
            ['mobile', '=', $MobileNo]
        );

        $userInfo = DB::table('users')->where($where)->first();
        if(!$userInfo){
            EE('您的帐号不存在',0, 10080);
        }
        /* if(!check_password_format($LoginPwd)){
             EE('密码必须是6-16位字母数字下划线组合');
         }*/
        $md5password = md5($LoginPwd);
        if ($md5password != $userInfo->password) {
            EE('密码错误',0,10081);
        }
        if ($userInfo->status == 0){
            EE('您的帐号存在异常，如有疑问，请联系客服!',0,10082);
        }

        // 校验是否需要发送下线通知
        $ticket = UserService::login_send_jpush($userInfo, ['mobile_unique_code'=>$mobile_unique_code, 'registration_id'=>$registration_id, 'ClientSource'=>$ClientSource]);

        $tags = Usertags::where('uid','=',$userInfo->id)->where('status','=',1)->value('tags');
        if(empty($ticket)){
            EE('登陆失败！',0, 10083);
        }
        /*   if(empty($tags)){
                EE('请选则你喜欢的栏目！');
            }*/
        $data = [
            'ticket' => $ticket,
            'uid' => $userInfo->id,
            'mobile' => $MobileNo,
            'tags'=> $tags
        ];
        $hx_user = HxUsers::where([['uid', '=', $userInfo->id]])->first();
        $data['hx_username'] = empty($hx_user) ? '' : $hx_user->hx_username;
        $data['hx_password'] = empty($hx_user) ? '' : $hx_user->hx_password;

        return json_success('登录成功',$data,10084);
    }

    /**
     * @return array
     * 发送验证码
     */
    public function registerSms(){
        $expire = config('app.sms_expire');    //短信存活时间，单位分钟
        $mobile = IT('mobile');
        if(!preg_match('/^\d+$/i', $mobile))
        {
            EE('手机号必须为数字',0, 10074);
        }
        if($mobile <= 0)
        {
            EE('手机号码格式有误',0, 10085);
        }

        // 该手机短信请求时间存活为60秒
        $is_request = cache('bind_sms_request_'.$mobile, false);
        if($is_request){
            EE('请勿频繁请求，请耐心等待60秒',0,10086);
        }
        $sms_request_expire = config('app.sms_request_expire'); // 短信请求时间限制，单位分钟
        cache(['bind_sms_request_'.$mobile => $mobile], $sms_request_expire); // 设置请求时间限制缓存

        $authCode = create_smscode($mobile,$expire);
        $res = send_msg($mobile, $authCode);
        if($res){
            return json_success('验证码发送成功',[],10087);
        }
        return json_success('验证码发送失败',[],10088);
    }

    /**
     * @return array
     * 退出登录
     */
    public function logout(){
        $ticket = IT('ticket',true);
        $client_source = IT('ClientSource',true);
        $where = [
            'ticket'=> $ticket,
            'client_source' =>$client_source
        ];
        $user_info = DB::table('user_tickets')->where($where)->first();
        if($user_info){
            $res = DB::table('user_tickets')->where('ticket','=',$ticket)->update(['status'=>2]);
            if($res == 1){
                cache(['ticket_'.$client_source.$user_info->id => '']);
                // 缓存退出
                Redis::del($key = 'user:login:'.md5($ticket));
                return json_success('退出成功',[],10089);
            }
            return json_error('退出失败',[],10090);
        }
        return json_error('您未登陆，无法退出',[], 10091);
    }

    /**
     * @return array
     * 忘记密码
     */
    public function forgetPwd(){
        $mobile = IT('mobile',true,'请输入手机号',10070);
        $smscode = IT('smscode',true);
        $password = IT('password',true);

        // $userInfo = DB::table('users')->where([['mobile','=',$mobile]])->first();
        $userInfo = DB::table('users')->where('mobile','=',$mobile)->first();
        if(!$userInfo){
            EE('您的帐号不存在',0,10080);
        }
        if(!check_password_format($password)){
            EE('密码必须是6-16位字母数字下划线组合',0, 10075);
        }
        if(check_smscode($mobile,$smscode) === false){
            EE('验证码输入错误',0, 10092);
        }
        $password = md5($password);
        $res = DB::table('users')->where('mobile','=',$mobile)->update(['password'=>$password]);
        // $res = DB::table('users')->where([['mobile','=',$mobile]])->update(['password'=>$password]);

//        if($res == 1){
        return json_success('重置密码成功',[],10093);
//        }else{
//            return json_success('新密码修改失败');
//        }
    }
    /**
     * 验证登录
     * @return array
     */
    public function VerifyLogin(){
        $mobile = IT('mobile',true,'请输入手机号',10070);
        $smscode = IT('smscode',true,'请输入验证码',10071);
        $ClientSource = IT('ClientSource',true);
        $ClientSource = IT('ClientSource',true);
        $registration_id = IT('registration_id');
        $mobile_unique_code = IT('mobile_unique_code',true,'移动设备唯一标识必填',10073);

        if(!preg_match('/^\d+$/i', $mobile))
        {
            EE('手机号必须为数字',0,10074);
        }
        if($mobile <= 0)
        {
            EE('手机号码格式有误',0,10074);
        }
        $userInfo = DB::table('users')->where('mobile','=',$mobile)->first();
        if(!$userInfo){
            EE('您的帐号不存在',0,10080);
        }

        if(check_smscode($mobile,$smscode) === true){

            // 校验是否需要发送下线通知
            $ticket = UserService::login_send_jpush($userInfo, ['mobile_unique_code'=>$mobile_unique_code, 'registration_id'=>$registration_id, 'ClientSource'=>$ClientSource]);
            $tags = Usertags::where('uid','=',$userInfo->id)->where('status','=',1)->value('tags');
            if(empty($ticket)){
                EE('登陆失败！',0,10083);
            }

            /*if(empty($tags)){
            EE('请选则你喜欢的栏目！');
            }*/
            $data = [
                'ticket' => $ticket,
                'uid' => $userInfo->id,
                'tags' =>$tags,
            ];
            $hx_user = HxUsers::where([['uid', '=', $userInfo->id]])->first();
            $data['hx_username'] = empty($hx_user) ? '' : $hx_user->hx_username;
            $data['hx_password'] = empty($hx_user) ? '' : $hx_user->hx_password;
            return json_success('ok',$data);
        }else{
            $data = [ ];
            return json_error('验证码不正确',$data,10092);
        }

    }

    //手机号码检测
    public function VerifyNumber(){

        $mobile = IT('mobile',true,'请输入手机号',10070);
        if(!preg_match('/^\d+$/i', $mobile))
        {
            EE('手机号必须为数字',0,10074);
        }
        if($mobile <= 0)
        {
            EE('手机号码格式有误',0, 10085);
        }
        $userInfo = DB::table('users')->where('mobile', $mobile)->first();//检测手机号码是不是已存在
        if($userInfo && !empty($userInfo->password)) {
            $data = [
                'status'=> 0
            ];
            return json_success('ok',$data, 10000);
        }else{
            $data = [
                'status'=>1,
            ];
            return json_success('ok',$data,10000);
        }
    }

    /**
     * 标签列表
     */
    public function TagsName()
    {
        /*  $page = intval(IT('page')) ? : 1;
          $page -= 1;*/
        $pageSize = config('admin.pageSize');
        $type = IT('type');
        $order_by = ($type == 1) ? 'DESC' : 'ASC';
        $tags = Tagsname::orderBy('id', $order_by)->get(['id','tags_name', 'type_code'])->toArray();
        if($tags && ($type == 1)) {
            $transcribe_tag = [];
            foreach($tags as $key => $tag) {
                if($tag['tags_name'] == '录屏') {
                    $transcribe_tag[] = $tag;
                    unset($tags[$key]);
                }
            }

            $tags = array_merge($transcribe_tag, $tags);
        }
        /* $tags = Tagsname::skip($page*$pageSize)->take($pageSize)->get(['id','tags_name']);*/
        return json_success('ok',$tags,10000);
    }
    /**
     * 标签选择
     * @param Request $request
     * @return array
     * @throws \App\Exceptions\ApiException
     */
    public function ChoiceTags(Request $request){
        $user = User::getUserInfo($request->ticket);
        $tags_name = $request->input('tags_name');
        $data = [
            'tags'=>$tags_name,
            'uid'=> $user->id,
            'status' =>1,
        ];
        $user_data = Usertags::where('uid','=',$user->id)->where('status','=',1)->first(['uid']);
        if($user_data){
            return json_error('你已经选择过了',[], 10094);
        }
        $tags = Usertags::insert($data);
        if($tags){
            return json_success('ok',[],10000);
        }else{
            return json_error('选择失败',[],10095);
        }
    }
}